const sdk = require('./build/Release/NodeHCNetSDK');
const express = require('express');
const fs = require("fs");

let app = express();
let index = 1;

// 设备信息
let devices = {
    '0001' : {
        ip : '192.168.100.1',
        port : 566,
        user : 'admin',
        pwd : 'admin',
        loginHandle : -1,
        chanel : {
            '0' : {
                playHandle : -1,
                file : '',
            },
            '1' : {
                playHandle : -1,
            }
        }
    },
    '0002' : {
        ip : '192.168.100.2',
        port : 566,
        user : 'admin',
        pwd : 'admin',
        loginHandle : -1,
        chanel : {
            '0' : {},
            '1' : {},
        }
    },
    '0003' : {
        ip : '192.168.100.3',
        port : 566,
        user : 'admin',
        pwd : 'admin',
        loginHandle : -1,
        chanel : {
            '0' : {},
            '1' : {},
        }
    }
};

// 状态查看
app.get('/state', function(req, res) {
    var data = JSON.stringify(devices);
    res.status(200).send(data);
});

// 播放 http://localhost/play?id=0001&chanel=0
app.get('/play', function(req, res){
    let id     = req.query.id;
    if( !devices.hasOwnProperty(id) ) {
        res.status(400).send('err id 不合法');
        return;
    }
    if(devices[id].loginHandle < 0) {
        // 未登录设备需要登录
        devices[id].loginHandle = sdk.Node_DVR_Login(devices[id].ip, devices[id].port, devices[id].user, devices[id].pwd);
    }
    if( devices[id].loginHandle <0 ) {
        res.status(400).send('err 登录失败');
        return;
    }

    //播放
    let chanel = req.query.chanel;
    if( !devices[id].chanel.hasOwnProperty(chanel) ) {
        res.status(400).send('err chanel 不合法');
        return;
    }
    if(devices[id].chanel[chanel].playHandle >= 0) {
        res.status(400).send('err 已经在播放');
        return;
    }
    devices[id].chanel[chanel].playHandle = sdk.Node_DVR_RealPlay(devices[id].loginHandle, chanel, 0);
    if(devices[id].chanel[chanel].playHandle < 0) {
        res.status(400).send('err 播放失败');

        let hasplay = false;
        for(var c in devices[id].chanel) {
            if (devices[dev].chanel.hasOwnProperty(c)) {
                if(devices[dev].chanel[c].playHandle >= 0) {
                    hasplay = true;
                    break;
                }
            }
        }
        if (!hasplay) {
            //退出登录
            if(!sdk.Node_DVR_Logout(devices[dev].loginHandle))
            {
                console.log('登出失败');
            }
            devices[dev].loginHandle = -1;

            res.status(200).send('播放失败并退出登录');
            return;
        }

        res.status(200).send('播放失败');
        return;
    }

    devices[id].chanel[chanel].file = './'+id+'-'+chanel+'-'+ index++ +'.ps';
    res.status(200).send('sucess 播放开始');
});

// 停止 http://localhost/stop?handle=005
app.get('/stop', function(req, res){
    let handle     = req.query.handle;

    //停止播放
    if(false == sdk.Node_DVR_RealStop(parseInt(handle))) {
        console.log('停止播放失败');
        res.send('停止播放失败');
        return;
    }

    //检查退出
    let finddev = false;
    for(var dev in devices) {
        if(devices.hasOwnProperty(dev) && devices[dev].loginHandle >= 0) {
            for(var c in devices[dev].chanel) {
                if (devices[dev].chanel.hasOwnProperty(c)) {
                    if(devices[dev].chanel[c].playHandle == handle) {
                        devices[dev].chanel[c].playHandle = -1;
                        finddev = true;
                        break;
                    }
                }
            }

            if(finddev) {
                let hasplay = false;
                for(var c in devices[dev].chanel) {
                    if (devices[dev].chanel.hasOwnProperty(c)) {
                        if(devices[dev].chanel[c].playHandle >= 0) {
                            hasplay = true;
                            break;
                        }
                    }
                }
                if (!hasplay) {
                    //退出登录
                    if(!sdk.Node_DVR_Logout(devices[dev].loginHandle))
                    {
                        console.log('登出失败');
                    }
                    devices[dev].loginHandle = -1;

                    res.status(200).send('停止播放并退出登录');
                    return;
                }
                break;
            }
        }
    }

    res.status(200).send('停止播放不退出');
});


// 视频回调方法
function video_cb(playHandle, buff)
{
    //如果遍历map
    for(var dev in devices) {
        if(devices.hasOwnProperty(dev)) {
            for(var c in devices[dev].chanel) {
                if (devices[dev].chanel.hasOwnProperty(c)){
                    // 保存buff到文件
                    if(devices[dev].chanel[c].playHandle == playHandle)
                    var fd = fs.writeFile(devices[dev].chanel[c].file, buff, {'flag': 'a'}, function (err) {
                        if (err){
                          console.log('文件写入失败',err.message);
                        };
                            console.log('写文件ok');
                            return;
                      });
                }
            }
        }
    }
}

// 任务结束回调方法
function final_cb()
{
    console.log('threadsafe_function finish');
}

// sdk初始化
sdk.Node_DVR_Init(video_cb, final_cb);

// 启动服务
var server = app.listen(80, function () {   
    console.log("启动成功");
});